package com.king.first.app.side;

import com.king.first.bean.WaterSensor;
import com.king.first.utils.ContentUtils;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink_Water_side_split {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env.socketTextStream(ContentUtils.HOST, 9999).map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        });

        SingleOutputStreamOperator<WaterSensor> result = waterSensorStream.keyBy(value -> value.getTs())
                .process(new KeyedProcessFunction<Long, WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor value, KeyedProcessFunction<Long, WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        out.collect(value);
                        if (value.getVc() > 5) { //水位大于5的写入到侧输出流
                            ctx.output(new OutputTag<WaterSensor>("警告") {
                            }, value);
                        }
                    }
                });

        result.print("主流");
        result.getSideOutput(new OutputTag<WaterSensor>("警告"){}).print("警告");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
